package com.example.library.interceptor;

import com.example.library.constant.Constants;
import com.example.library.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: asus
 * Date: 2024-12-21
 * Time: 0:16
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 目标方法执行前执行
     * @param request
     * @param response
     * @param handler
     * @return true, 继续后续操作; false: 被拦截
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("登录拦截器");
//        HttpSession session = request.getSession(false);//true, 没有session就创建session; false, 没有就直接返回
//        if (session != null && session.getAttribute(Constants.SESSION_USER_KEY) != null) {
//            UserInfo userInfo = (UserInfo) session.getAttribute(Constants.SESSION_USER_KEY);
//            if (userInfo != null && userInfo.getId() >= 0) {
//                return true;
//            }
//        }
        HttpSession session = request.getSession();
        UserInfo userInfo = (UserInfo) session.getAttribute(Constants.SESSION_USER_KEY);
        if (userInfo != null && userInfo.getId() >= 0) {
            return true;
        }
        response.setStatus(401);//未认证登录

        return false;
    }

    /**
     * 目标方法执行后执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        log.info("目标方法执行后");
//    }

    /**
     * 视图渲染后执行
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
